# src/models/Portfolio.py
from . import db
import datetime
from marshmallow import fields, Schema

class PortfolioModel(db.Model):
  """
  Portfolio Model
  """

  __tablename__ = 'portfolios'

  id = db.Column(db.Integer, primary_key=True)
  code = db.Column(db.String(20), nullable=False)
  name = db.Column(db.String(30), nullable=False)
  market_id = db.Column(db.Integer, db.ForeignKey('markets.id'), nullable=False)   # 1: 香港市场 2: 美国市场 3: 大陆市场 4: 香港A股通市场 5: 期货市场
  currency_id = db.Column(db.Integer, db.ForeignKey('currencies.id'), nullable=False)  # 1: 港币 2: 美元 3: 离岸人民币
  prev_close_price = db.Column(db.Float)
  last_price = db.Column(db.Float)
  change_rate = db.Column(db.Float)  
  volume = db.Column(db.Integer)
  volume_ratio = db.Column(db.Float)    # 量比
  turnover = db.Column(db.Float)
  turnover_rate = db.Column(db.Float)    # 换手率
  dividend_ratio_ttm = db.Column(db.Float)  # 股息率

  reminder_PriceUp = db.Column(db.Float)          # 价格涨到
  reminder_PriceDown = db.Column(db.Float)       # 价格跌到
  reminder_ChangeRateUp = db.Column(db.Integer)     # 日涨幅超，该字段为百分比字段，设置时填20表示20%
  reminder_ChangeRateDown = db.Column(db.Integer)  
  created_at = db.Column(db.DateTime)
  modified_at = db.Column(db.DateTime)
 
  def __init__(self, data):
    self.code = data.get('code')
    self.name = data.get('name')
    self.market_id = data.get('market_id')
    self.currency_id = data.get('currency_id')
    self.created_at = datetime.datetime.utcnow()
    self.modified_at = datetime.datetime.utcnow()

  def save(self):
    db.session.add(self)
    db.session.commit()

  def update(self, data):
    for key, item in data.items():
      setattr(self, key, item)
    self.modified_at = datetime.datetime.utcnow()
    db.session.commit()

  def delete(self):
    db.session.delete(self)
    db.session.commit()
  
  @staticmethod
  def get_all_portfolios():
    return PortfolioModel.query.all()
  
  @staticmethod
  def get_one_portfolio(code):
    return PortfolioModel.query.get(code)

  def __repr__(self):
    return '<code {}>'.format(self.code)

class PortfolioSchema(Schema):
  """
  Portfolio Schema
  """
  id = fields.Int(dump_only=True)
  code = fields.Str(required=True)
  name = fields.Str(required=True)
  market_id = fields.Int(required=True)   # 1: 香港市场 2: 美国市场 3: 大陆市场 4: 香港A股通市场 5: 期货市场
  currency_id = fields.Int(required=True)  # 1: 港币 2: 美元 3: 离岸人民币

  prev_close_price = fields.Float(dump_only=True)
  last_price = fields.Float(dump_only=True)
  change_rate = fields.Float(dump_only=True)
  volume = fields.Int(dump_only=True)     
  volume_ratio = fields.Float(dump_only=True)         # 量比
  turnover = fields.Float(dump_only=True)
  turnover_rate = fields.Float(dump_only=True)        # 换手率
  
  # total_market_val
  # pe_ratio
  # pb_ratio
  dividend_ratio_ttm = fields.Float(dump_only=True)   # 股息率

  reminder_PriceUp = fields.Float(dump_only=True)          # 价格涨到
  reminder_PriceDown = fields.Float(dump_only=True)       # 价格跌到
  reminder_ChangeRateUp = fields.Float(dump_only=True)     # 日涨幅超，该字段为百分比字段，设置时填20表示20%
  reminder_ChangeRateDown = fields.Float(dump_only=True)   # 日跌幅超，该字段为百分比字段，设置时填20表示20%
  created_at = fields.DateTime(dump_only=True)
  modified_at = fields.DateTime(dump_only=True)

'''
        required int32 trdSide = 1; //交易方向, 参见TrdSide的枚举定义
        required uint64 fillID = 2; //成交号
        required string fillIDEx = 3; //扩展成交号(仅查问题时备用)
        optional uint64 orderID = 4; //订单号
        optional string orderIDEx = 5; //扩展订单号(仅查问题时备用)
        required string code = 6; //代码
        required string name = 7; //名称
        required double qty = 8; //成交数量，2位精度，期权单位是"张"
        required double price = 9; //成交价格，3位精度
        required string createTime = 10; //创建时间（成交时间），严格按YYYY-MM-DD HH:MM:SS或YYYY-MM-DD HH:MM:SS.MS格式传
        optional int32 counterBrokerID = 11; //对手经纪号，港股有效
        optional string counterBrokerName = 12; //对手经纪名称，港股有效
        optional int32 secMarket = 13; //（2018/07/17新增）证券所属市场
'''